<template>
  <div class="body">
    <div class="table-wrap">
      <div class="search_header">
        <span>
          <el-button
            v-has="'mapManagement:add'"
            icon="el-icon-plus"
            @click="
              ;(dialogVisible = true),
                (add = true),
                (headerTitle = '新增底图')
            "
            >新增底图
          </el-button>
        </span>
        <div class="search_header_right">
          <el-input
            placeholder="请输入底图名称"
            @change="searchMap"
            v-model="query.name"
          >
            <span
              @click="searchMap"
              slot="suffix"
              style="display: inline-block"
            >
              <Icon
                title="搜索"
                name="sousuo"
                color="#A7ADB5"
                font-size="20"
              />
            </span>
          </el-input>
        </div>
        <!-- <el-select
            v-model="query.serviceType"
            clearable
            @change="searchMap"
          >
            <el-option
              v-for="item in formData"
              :key="item.name"
              :label="item.name"
              :value="item.value"
            />
          </el-select> -->
      </div>
      <el-table
        :data="mapList"
        :header-cell-style="{
          background: '#F2F6FB ',
          color: ' #6B767D'
        }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          label="底图名称"
          prop="name"
          show-overflow-tooltip
        />
        <el-table-column label="缩略图">
          <template slot-scope="scope">
            <el-image
              alt=""
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
              style="height: 45px; width: 45px"
            >
            </el-image>
          </template>
        </el-table-column>
        <!-- <el-table-column
              label="服务地址"
              prop="mapUrl"
              show-overflow-tooltip
            /> -->
        <el-table-column label="是否默认">
          <template slot-scope="scope">
            {{ scope.row.isDefault === 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          prop="updateTime"
          show-overflow-tooltip
        />
        <!-- <el-table-column
              label="数据类型"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ funtypeFun(scope.row.serviceType) }}
              </template>
            </el-table-column> -->
        <!--          <el-table-column label="是否为默认">-->
        <!--            <template slot-scope="scope">-->
        <!--              <el-switch-->
        <!--                v-model="scope.row.isDefault"-->
        <!--                style="margin-left: 20px"-->
        <!--                disabled-->
        <!--                :active-value="1"-->
        <!--                :inactive-value="0"-->
        <!--              />-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="Update(scope.row)"
              style="color: #00baff; font-weight: 400"
              v-has="'mapManagement:edit'"
              >编辑
            </el-button>
            <el-button
              type="text"
              @click="deleteMap(scope.row)"
              style="color: #ff5b5b; font-weight: 400"
              v-has="'mapManagement:delete'"
              >删除
            </el-button>
            <i
              v-if="scope.row.index !== 0"
              @click.stop="moveSort(scope.row, -1)"
              v-has="'catalogueManagement:edit'"
              class="el-icon-top"
              title="向上移动"
              style="
                font-size: 16px;
                float: right;
                margin-right: 10px;
                color: #00baff;
                line-height: 36px;
                cursor: pointer;
              "
            ></i>
            <i
              v-if="scope.row.index !== mapList.length - 1"
              @click.stop="moveSort(scope.row, 1)"
              v-has="'catalogueManagement:edit'"
              class="el-icon-bottom"
              title="向下移动"
              style="
                font-size: 16px;
                float: right;
                margin-right: 10px;
                color: #00baff;
                line-height: 36px;
                cursor: pointer;
              "
            ></i>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination" v-if="total">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-size="query.pageSize"
          @current-change="pageChange"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      @opened="onOpen"
      @close="onClose"
      :title="headerTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="620px"
      top="5vh"
    >
      <el-form
        :model="addList"
        :rules="rules"
        label-width="80px"
        ref="ruleForm"
      >
        <el-form-item label="底图名称" prop="name">
          <el-input v-model="addList.name" clearable />
        </el-form-item>
        <el-form-item label="服务地址" prop="mapUrl">
          <el-input v-model="addList.mapUrl" clearable />
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select
            v-model="addList.serviceType"
            clearable
          >
            <el-option
              v-for="item in formData"
              :key="item.name"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否默认">
          <el-switch
            v-model="addList.isDefault"
            style="margin-left: 20px"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="缩略图">
          <el-upload
            action="#"
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            accept="image/*"
          >
            <el-image
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            >
              <!-- <div slot="error" class="image-slot">
                <div></div>
              </div> -->
            </el-image>
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            />
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onClose">取消</el-button>
        <el-button
          type="primary"
          @click="onSubmit('ruleForm')"
          >确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadImage,
  padQuery,
  padInsert,
  padUpdate,
  padDelete,
  padServiceAdd,
  padServiceDelete,
  padServiceUpdate,
  padServiceQuery,
  padBasemapUpdateSort
} from '@/api/pad'
import { noticeFileUpload } from '@/api/wisdomBuild'
import Icon from '@/components/icon'
import { STATIC_FILE_URL } from '@/api/config.js'

export default {
  name: 'index',
  components: {
    Icon
  },
  data() {
    return {
      mapList: [],
      imageUrl: '',
      addList: {
        name: '',
        serviceName: '',
        mapUrl: '',
        terrainUrl: '',
        isDefault: 0,
        serviceType: '',
        // terrainType:'',
        isDefaultData: 0,
        fileId: ''
      },
      formData: [
        // {
        //   name: 'WMTS',
        //   value: 21
        // },
        // {
        //   name: 'XYZ_Tiles',
        //   value: 22
        // },
        {
          name: '矢量切片服务',
          value: 23
        },
        {
          name: 'WMS',
          value: 24
        },
        // {
        //   name: 'ArcGIS',
        //   value: 25
        // },
        {
          name: 'REST 服务',
          value: 26
        },
        // {
        //   name: 'RealSpace 服务',
        //   value: 27
        // },
        {
          name: '天地图',
          value: 28
        }
      ],
      pkid: '',
      rules: {
        name: [
          {
            required: true,
            message: '请输入底图名称',
            trigger: 'blur'
          }
        ],
        serviceName: [
          {
            required: true,
            message: '请输入数据名称',
            trigger: 'blur'
          }
        ],
        mapUrl: [
          {
            required: true,
            message: '请输入服务地址',
            trigger: 'blur'
          }
        ],
        serviceType: [
          {
            required: true,
            message: '请选择底图的数据类型',
            trigger: 'blur'
          }
        ]
      },
      query: {
        pageSize: 10,
        pageIndex: 1,
        serviceType: '',
        name: ''
      },
      total: '',
      headerTitle: '新增底图',
      add: true,
      dialogVisible: false,
      editableTabsValue: '1',
      editableTabs: [],
      tabIndex: 1,
      resourceMapBaseServiceInfos: [],
      pictureFile: null
    }
  },
  mounted() {
    this.getList()
  },
  computed: {
    staticFileUrl() {
      return STATIC_FILE_URL
    }
  },
  methods: {
    async moveSort(row, direction) {
      if (this.loading) return
      this.loading = true
      try {
        const curIndex = row.index
        const nextIndex = row.index + direction
        const curPkid = row.pkid
        const nextPkid =
          this.mapList[row.index + direction].pkid
        const idList = this.mapList.map((e, index) => {
          let ret = e.pkid
          if (e.index == curIndex) {
            ret = nextPkid
          } else if (e.index == nextIndex) {
            ret = curPkid
          }
          return ret
        })
        await padBasemapUpdateSort({
          pkidList: idList,
          pageIndex: this.query.pageIndex,
          pageSize: this.query.pageSize
        })
        await this.getList()
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    getImageSrc(row) {
      if (row.fileList && row.fileList.length) {
        return `${STATIC_FILE_URL}${row.fileList[0].filePath}`
      } else {
        return row.picture
      }
    },
    deleteMapService(id) {
      this.$confirm(
        '此操作将永久删除该数据服务，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then((e) => {
        padServiceDelete(id).then((res) => {
          if (res.success) {
            this.$message.success(res.data)
            // this.getMapInfo(this.pkid)
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    // 编辑
    Update(item) {
      this.add = false
      this.headerTitle = '编辑底图'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.pkid = item.pkid
        this.addList.mapUrl = item.mapUrl
        this.addList.name = item.name
        this.addList.isDefault = item.isDefault
        // this.imageUrl = item.picture
        this.imageUrl = this.getImageSrc(item)
        this.addList.serviceType = Number(item.serviceType)
      })

      // this.getMapInfo(item.pkid)
    },
    // 删除
    deleteMap(item) {
      this.$confirm(
        '此操作将永久删除该数据，是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          padDelete(item.pkid).then((res) => {
            if (res.success) {
              this.$message.success(res.data)
              this.getList()
            } else {
              this.$message.error(res.message)
            }
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    searchMap() {
      this.query.pageIndex = 1
      this.getList()
    },
    pageChange(page) {
      this.query.pageIndex = page
      this.getList()
    },
    // onClose
    onClose() {
      this.dialogVisible = false
      this.addList.name = ''
      this.addList.serviceName = ''
      this.addList.mapUrl = ''
      this.addList.isDefault = 0
      this.addList.serviceType = ''
      this.addList.fileId = ''
      this.pkid = ''
      this.imageUrl = ''
      this.pictureFile = ''
      this.getList()
    },
    onOpen() {
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
      })
    },
    // 添加
    onSubmit(ruleForm) {
      this.$refs[ruleForm].validate((vaild) => {
        if (vaild) {
          const form = new FormData()
          form.append('pictureFile', this.pictureFile)
          const queryString = new URLSearchParams(
            this.addList
          ).toString()
          if (this.add) {
            padInsert(
              this.pictureFile ? form : '',
              queryString
            ).then((res) => {
              if (res.success) {
                this.$message.success('新增底图成功')
                this.onClose()
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            padUpdate(
              this.pictureFile ? form : '',
              queryString,
              this.pkid
            ).then((res) => {
              if (res.success) {
                this.$message.success(res.data)
                this.onClose()
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    },
    getList() {
      padQuery(this.query).then((res) => {
        if (res.success) {
          this.mapList = res.data.list.map((e, index) => {
            return {
              ...e,
              index,
              url: this.getImageSrc(e)
            }
          })
          this.total = res.data.count
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getFileType(name) {
      const startIndex = name.lastIndexOf('.')
      if (startIndex !== -1) {
        return name.slice(startIndex + 1).toLowerCase()
      } else {
        return ''
      }
    },
    // 上传
    beforeUpload(file) {
      const suffix = this.getFileType(file.name)
      const suffixArray = ['png', 'jpg', 'jpeg']
      if (suffixArray.indexOf(suffix) === -1) {
        this.$message({
          message: '文件格式错误',
          type: 'error',
          duration: 2000
        })
        return false
      }
      this.pictureFile = file
      // this.getBase64(file).then((res) => {
      //   this.imageUrl = res
      // })
      console.log('before upload file ', file)
      const image = new FormData()
      image.append('file', file)
      noticeFileUpload(image).then((res) => {
        if (res.success) {
          this.addList.fileId = res.data
          this.addList.picture = res.data
          this.getBase64(file).then((res) => {
            this.imageUrl = res
            console.log(this.imageUrl)
          })
        } else {
          this.$message.error(res.message)
        }
      })
      return false
    },
    // base64转换
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    imageToBase64(img) {
      // 创建画布
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height

      // 绘制图片到画布
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, img.width, img.height)

      // 获取 Base64 编码
      return canvas.toDataURL('image/png')
    },
    getBase64Image(url) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.src = url // 替换为实际图片路径
        img.onload = function () {
          const base64Data = imageToBase64(img)
          resolve(base64Data)
        }
        img.onerror = function (error) {
          reject(error)
        }
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'light'
      } else {
        return ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '~@/assets/css/table.scss';
.body ::v-deep {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .light {
    background: #f9fcff;
    border: 1px solid #f2f6fb !important;
  }

  .body_main_header {
    .el-select {
      float: right;
      margin-right: 10px;
    }

    .el-button {
      background: #497fa3 !important;
      color: white !important;
      border: none !important;
      border-radius: 2px;
    }

    .el-input {
      width: 300px !important;
      float: right;

      .el-button {
        background: #f5f7fa !important;
        color: #a9acb1 !important;
      }
    }
  }

  .el-tabs__item:focus.is-active {
    box-shadow: none !important;
  }

  .el-dialog {
    .el-dialog__header {
      background: #597182 !important;
      padding: 8px 0 14px 24px !important;
      height: 39px !important;

      .el-dialog__title {
        font-size: 16px !important;
        line-height: 22px;
        font-weight: 400 !important;
        color: white !important;
        //margin:19px 0 14px 24px !important;
      }

      .el-dialog__headerbtn {
        font-size: 16px;
        top: 10px !important;
        right: 17px !important;
        color: white !important;

        .el-dialog__close {
          color: white !important;
        }
      }
    }

    .el-dialog__body {
      padding: 17px 32px 18px 26px !important;

      .el-form-item {
        margin-bottom: 19px !important;
      }

      .el-tabs {
        // 居中
        //&__nav-scroll {
        //  width: 50%;
        //  margin: 0 auto;
        //}

        //&__header {
        //  margin-left: 20px;
        //}

        &__nav-wrap::after {
          position: static !important;
        }

        &__active-bar {
          background-color: #497fa3;
          width: 30px !important;
          // margin-left: 10px;
        }

        &__item {
          &.is-active {
            color: #497fa3;
          }

          &:not(:last-of-type) {
            &:after {
              content: '';
              height: 30%;
              width: 1px;
              position: absolute;
              right: 0;
              top: 35%;
              background-color: #d0d8e1;
            }
          }
        }
      }
    }

    .el-input__inner {
      //height: 34px !important;
      background-color: #f6f9fc !important;
    }

    .el-button--default {
      border-color: #497fa3 !important;

      span {
        color: #497fa3 !important;
      }
    }

    .el-button--primary {
      background: #497fa3 !important;
      border-color: white !important;
    }
  }
}
</style>
